﻿#if NETFX_CORE
using Windows.Foundation;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
#else
using System.Windows;
using System.Windows.Controls;
#endif

namespace FreshMeat.Xaml
{
   public class DragGridHelper
   {
      public static void PositionOnGrid(Grid grid, Point targetPosition, FrameworkElement element)
      {
         var column = 0;
         var left = 0.0;
         if (targetPosition.X > left && grid.ColumnDefinitions.Count > 0)
         {
            foreach (var definition in grid.ColumnDefinitions)
            {
               var right = left + definition.ActualWidth;
               if (targetPosition.X >= left && targetPosition.X <= right)
                  break;

               left = right;
               column++;
            }
            if (column >= grid.ColumnDefinitions.Count)
               column--;
         }

         var row = 0;
         var top = 0.0;
         if (targetPosition.Y > top && grid.RowDefinitions.Count > 0)
         {
            foreach (var definition in grid.RowDefinitions)
            {
               var bottom = top + definition.ActualHeight;
               if (targetPosition.Y >= top && targetPosition.Y <= bottom)
                  break;

               top = bottom;
               row++;
            }
            if (row >= grid.RowDefinitions.Count)
               row--;
         }

         Grid.SetColumn(element, column);
         Grid.SetRow(element, row);
      }
   }
}
